package club.ruanx.security;

import club.ruanx.security.handler.LoginSuccessHandler;
import club.ruanx.security.service.AdminDetailServiceImpl;
import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

/**
 * @author 阮胜
 * @date 2019/1/6 20:05
 */
@Configuration
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {

    private final String adminContextPath;
    private final AdminDetailServiceImpl adminDetailService;
    private final LoginSuccessHandler loginSuccessHandler;

    public AdminSecurityConfig(AdminServerProperties adminServerProperties, AdminDetailServiceImpl adminDetailService) {
        this.adminContextPath = adminServerProperties.getContextPath();
        this.adminDetailService = adminDetailService;
        this.loginSuccessHandler = new LoginSuccessHandler(adminContextPath);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
                .anyRequest().authenticated()
                .and()
                .userDetailsService(adminDetailService)
                .formLogin().loginPage(adminContextPath + "/login")
                .successHandler(loginSuccessHandler).and()
                .logout().logoutUrl(adminContextPath + "/logout").and()
                .httpBasic().and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringAntMatchers(adminContextPath + "/instances", adminContextPath + "/actuator/**");
    }

}
